package com.eva.apidoc.knife4j;
import com.eva.apidoc.ApiDocProperties;
import com.eva.framework.config.AppProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Swagger拦截器
 */
@Slf4j
@Component
public class Knife4jInterceptor implements HandlerInterceptor {

    @Resource
    private AppProperties appProperties;

    @Resource
    private ApiDocProperties apiDocProperties;

    @Override
    @SuppressWarnings("NullableProblems")
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 禁用 || 生产环境，均视为禁用了接口文档
        if (!apiDocProperties.getEnabled() || appProperties.isProductionEnv()) {
            String uri = request.getContextPath();
            if (StringUtils.isNotBlank(apiDocProperties.getRedirectUri()))
                uri = request.getContextPath() + apiDocProperties.getRedirectUri();
            if (StringUtils.isBlank(uri))
                uri = "/";
            try {
                response.sendRedirect(uri);
            } catch (IOException e) {
                log.error(String.format("接口文档未启用，重定向到 '%s' 出现了错误 : %s", uri, e.getMessage()), e);
            }
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }
}
